import { queryMenus, queryContent, queryBaseUserInfo } from '@/api/base';
import { postLogout } from '@/api/login.js';
import { commonDownload } from '@/api/common';
import routerPageMap from '@/router/routerPageMap';
import { generateAsyncRouter } from '@/router/util';
import config from '@/config/index';
import store from '@/store/store';
import { getInfo } from '@/api/login';
import { BaseStatusEnum, BaseSysStatusEnum } from '../enum/enum';
import { storageGet } from '@/appBase/zkStorage';
import { politicalAffiliationDic, nationDic, sexDic, mLevelDic, pLevelDic, mPostDic, pPostDic } from './dic';
import allIcon from './icons';
import { toQueryString } from '@zkey-webapp/general';
import QS from 'qs';
/**
* 拉取动态路由信息
*/
export function getDynamicRouter(store) {
    const sortId = (a, b) => {
        return a.sort - b.sort;//由低到高
    }
    if (config.env == config.EnvEnum.DEV||config.env == config.EnvEnum.DEV_TEST) {
        // 开发阶段拉取本地模拟全量的导航菜单配置
        return Promise.all([import('@/router/dynamicRouterMap')]).then((res) => {
            const result = res[0];
            const arr = res[0].default;
            return generateAsyncRouter(arr, routerPageMap);
        });
    }
    return queryMenus().then((result) => {
        const createTreeNode = (menusNode,pNode)=>{
            let { path, meta,children} = menusNode;
            if (!meta) {
                meta = {};
            }
            if (pNode&&path.indexOf('/')!=0) {
                // 相对路径改为绝对路径
                path =`${pNode.path}/${path}`;
            }
            const node = {
                path,
                meta: {
                    title:meta.title,
                    icon:allIcon[meta.icon + 'Icon'] || meta.icon,
                    link:meta.link
                }
            }
            if (children) {
                node.children = children.map(i=>createTreeNode(i,node));
            }
            return node;
        }
        const arr = result.map(i=>createTreeNode(i,null));
        return generateAsyncRouter(arr, routerPageMap);
    });
}

/**
 * 退出登录
 * @param {*} ctx 
 * @param {Boolean} force 是否强制退出登录(不需服务端知晓的情况)
 * @returns 
 */
export function logout(ctx, force) {
    let prom = Promise.resolve();
    if (!force) prom = postLogout();
    const handleFunc = ()=>{
        store.commit('UpdateToken', null);
        store.commit('ClearNowUserInfo');
        ctx && ctx.$store.commit('UpdateDynamicRouter', null);
        setTimeout(() => {
            if (window.location.href.indexOf('#') > -1 && window.location.href.indexOf('_tk') < 0) {
                window.location.href = window.location.href.split('#')[0]
            } else {
                window.location.href = window.location.origin;
            }
        }, 500)
    }
    return prom.then((result) => {
        handleFunc();
        return result;
    }).catch((err)=>{
        handleFunc();
    })
}

export async function appStateInit() {
    try {
        const result = await getInfo()
        const nowUserInfo = result.user;
        nowUserInfo.permissions = result.permissions;
        nowUserInfo.hasVal = true;
        store.commit('UpdateNowUserInfo', nowUserInfo);
        // 更新用户拓展基本信息 
        const result1 = await queryBaseUserInfo()
        const { deptName, mLevel, pLevel, entryTime } = result1;
        store.commit('UpdateNowUserInfo', { deptName, mLevel, pLevel, entryTime });
        // sexDic.init();
        // politicalAffiliationDic.init();
        // nationDic.init();
        // mLevelDic.init();
        // pLevelDic.init();
        // mPostDic.init();
        // pPostDic.init();
    } catch (error) {
        console.log(error);   
    }
}

/**
 * 获取当前用户信息
 * 
 * @return {{
 *      doctorId: "医生Id"
 *      id: "用户id", userType=1 时为医生 Id,此外为 operatorId
 *      teamId: '工作室 id'
 *      name: "工作室名称"
 *      userName: "用户名称"
 *      permission: "权限1,权限2"
 *      token: "token",
 *      userType:1 1.医生 2.运营人员,
 *      operatorId: 运营人员 Id
 * }}
 */
export function getNowUserInfo() {
    const nowUserInfo = store.state.nowUserInfo;
    return nowUserInfo && nowUserInfo.hasVal == true ? nowUserInfo : null;
}

/**
 * 获取常规状态选项列表
 * @param {Number} type 0.常规 1.带额外全部选项
 */
export function getStatusOpts(type) {
    const arr = [
        { label: BaseStatusEnum.toStr(BaseStatusEnum.ENABLE), value: BaseStatusEnum.ENABLE },
        { label: BaseStatusEnum.toStr(BaseStatusEnum.DISABLED), value: BaseStatusEnum.DISABLED }
    ];
    if (type == 1) {
        arr.unshift({ label: BaseStatusEnum.toStr(BaseStatusEnum.ALL), value: BaseStatusEnum.ALL });
    }
    return Promise.resolve(arr);
}

/**
 * 获取系统管理状态选项列表
 * @param {Number} type 0.常规 1.带额外全部选项
 */
export function getSysStatusOpts(type) {
    const arr = [
        { label: BaseSysStatusEnum.toStr(BaseSysStatusEnum.ENABLE), value: BaseSysStatusEnum.ENABLE },
        { label: BaseSysStatusEnum.toStr(BaseSysStatusEnum.DISABLED), value: BaseSysStatusEnum.DISABLED }
    ];
    if (type == 1) {
        arr.unshift({ label: BaseSysStatusEnum.toStr(BaseSysStatusEnum.ALL), value: BaseSysStatusEnum.ALL });
    }
    return Promise.resolve(arr);
}

/**
 * 下载文件
 * @param fileName 文件名
 */
export function downloadFile(fileName) {
    window.location.href = `${config.apiRoot}${commonDownload}?fileName=${encodeURI(fileName)}`;
}

export function toQueryParamForSys(params) {
    return QS.stringify(params,{ arrayFormat: 'repeat' });;
}

/**
 * 检测用户归属角色
 * @param {Array<String>} rolesKeys 
 */
export function userInRoles(rolesKeys) {
    const user = getNowUserInfo();
    const { roles } = user;
    const item = roles.find(i=>rolesKeys.includes(i.roleKey));
    if(item){
        return true;
    }
    return false;
}

/**
 * 是否是管理员
 * @returns 
 */
export function userIsAdmin() {
   return userInRoles(['admin','R-Admin']);
}

